package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.CirclePictureAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.FansAndLike;
import com.voicechat.firstmet.bean.JsonBean;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.Params;
import com.voicechat.firstmet.net.service.FaintService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity
 * @ClassName: PublishShareGirlsActivity
 * @Description: 发布共享闺蜜信息
 * @Author: ljp
 * @CreateDate: 2019/1/5 11:16
 * @Version: 1.0
 */
public class PublishShareGirlsActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_send_share)
    TextView tvSendShare;
    @BindView(R.id.et_girls_name)
    EditText etGirlsName;
    @BindView(R.id.linear_chose)
    LinearLayout linearChose;
    @BindView(R.id.et_sex)
    EditText etSex;
    @BindView(R.id.et_age)
    EditText etAge;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_education)
    EditText etEducation;
    @BindView(R.id.et_redpacket)
    EditText etRedpacket;
    @BindView(R.id.et_phoneNumber)
    EditText etPhoneNumber;
    @BindView(R.id.et_back)
    EditText etBack;
    @BindView(R.id.tv_sum)
    TextView tvSum;
    @BindView(R.id.recycler_pictuer)
    RecyclerView recyclerPictuer;
    @BindView(R.id.tv_height)
    TextView tvHeight;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String deviceInfo;
    //选择图片list
    private List<LocalMedia> tlist;
    private CirclePictureAdapter circlePictureAdapter;
    private List<LocalMedia> selectList;
    private String nikName;
    private int sex;
    private String age;
    private String education;
    private String redPack;
    private String phoneNumber;
    private String info;
    private String height;
    private String weight;
    private String TAG = "PublishShareGirlsActivity";
    private OptionsPickerView pvNoLinkOptions;

    private OptionsPickerView pvNoLinkOptionsEdu;
    //身高和体重数据list
    private ArrayList<String> statureList;
    private ArrayList<String> weightList;

    private ArrayList<String> educationList;
    //城市数据list
    private ArrayList<JsonBean.DataBean> options1Items;
    private ArrayList<ArrayList<String>> options2Items;
    private String province;
    private String city;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_publish_share_girls;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
    }

    private void initView() {
        //身高体重数据实例化
        initJsonData();
        initStatue();
        initStatueEdu();
        initNoLinkOptionsPicker();
        initEduOptionsPicker();
        etBack.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                tvSum.setText(s.length() + "/100");
            }
        });
        tlist = new ArrayList<>();
        circlePictureAdapter = new CirclePictureAdapter(context, tlist, R.layout.item_send_post_picture, 3);
        recyclerPictuer.setLayoutManager(new GridLayoutManager(activity, 3));
        recyclerPictuer.setAdapter(circlePictureAdapter);
        circlePictureAdapter.addFooterView(R.layout.item_send_post_picture);
        circlePictureAdapter.setAddClick(new CirclePictureAdapter.OnAddClick() {
            @Override
            public void setAddItemClick(int position) {
                initPicture();
            }

            @Override
            public void setRemoveItemClick(int position) {
                tlist.remove(position);
                circlePictureAdapter.refreshCurrentAdapter();
            }

            @Override
            public void setSendImgBg(boolean flag) {
            }
        });
    }

    /**
     * @return
     * @method
     * @description 选择照片
     * @date: 2018/11/18 15:08
     * @author: ljp
     */
    private void initPicture() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(5)// 最大图片选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .compress(true)
                //.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //.isGif(true)// 是否显示gif图片 true or false
                .selectionMedia(tlist)// 是否传入已选图片 List<LocalMedia> list
                /*.freeStyleCropEnabled()// 裁剪框是否可拖拽 true or false
                .openClickSound()// 是否开启点击声音 true or false
                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false*/
                .cropCompressQuality(90)// 裁剪压缩质量 默认90 int*/
                .minimumCompressSize(1024)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    circlePictureAdapter.setList(selectList);
                    circlePictureAdapter.refreshCurrentAdapter();
                    break;
                case 100:
                    FansAndLike.PageBean.ListBean listBean = data.getParcelableExtra("bean");
                    etGirlsName.setText(listBean.getNickName());
                    tvHeight.setText(listBean.getHeight());
                    etAddress.setText(listBean.getProvince()+listBean.getAscription());
                    province = listBean.getProvince();
                    city = listBean.getAscription();
                    sex = Integer.parseInt(listBean.getGender());
                    height = Utils.spitHeight(listBean.getHeight(),0);
                    height = height.substring(0, height.length() - 2);
                    weight = Utils.spitHeight(listBean.getHeight(),1);
                    weight = weight.substring(0, weight.length() - 2);
                    if(sex == 1){
                        etSex.setText("男");
                    }else {
                        etSex.setText("女");
                    }
                    etAge.setText(Utils.getAge(listBean.getBirthday()));
                    break;
            }
        }
    }
    private void setPictureList() {
        List<LocalMedia> tlist = circlePictureAdapter.getTlist();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < tlist.size(); i++) {
            LocalMedia localMedia = tlist.get(i);
            list.add(localMedia.getCompressPath());
        }
        setOssHttp(list);
    }
    /**
     * @return
     * @method
     * @description 上传照片到oss
     * @date: 2018/11/18 17:08
     * @author: ljp
     */
    private void setOssHttp(List<String> list) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OssClient.getInstance().init(context).
                            ossUploads(list, new OssClient.OnUploadFile() {
                                @Override
                                public void onUploadFileSuccess(String info) {
                                    Log.i(TAG, "onUploadFileSuccess: -----" + info);
                                    publishShareGirlsHttp(info);
                                }
                                @Override
                                public void onUploadFileFailed(String errCode) {
                                }
                            }, new StringBuffer());
                } catch (ClientException e) {
                    e.printStackTrace();
                } catch (ServiceException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * @return
     * @method
     * @description 发布闺蜜信息
     * @date: 2019/1/16 16:47
     * @author: ljp
     */
    private void publishShareGirlsHttp(String path) {
        Params params = new Params();
        params.put("avatarUrl", path);
        params.put("nickName", nikName);
        params.put("age", Integer.valueOf(age));
        params.put("education", education);
        params.put("info", info);
        params.put("price", Integer.valueOf(redPack));
        params.put("relation", phoneNumber);
        params.put("address", city);
        params.put("province", province);
        params.put("height", Integer.valueOf(height));
        params.put("weight", Integer.valueOf(weight));
        params.put("userId", mySeleInfo.getId());//用户id
        params.put("token", SPUtils.getEditoString(SPUtils.SP_TOKEN));
        params.put("gender", sex);
        params.put("equipmentId", deviceInfo);
        FaintService.shareGirlsPublish(params).subscribe(result -> {
            Log.i(TAG, "publishShareGirlsHttp: --------------" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                Intent intent = new Intent(activity, AuditActivity.class);
                intent.putExtra("flag", 1);
                startActivity(intent);
                finish();
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                tvSendShare.setEnabled(true);
                Utils.setToken(context);
            } else {
                tvSendShare.setEnabled(true);
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "publishShareGirlsHttp: -----------" + throwable.toString());
            tvSendShare.setEnabled(true);
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }

    @OnClick({R.id.linear_back, R.id.tv_send_share, R.id.linear_chose, R.id.et_education, R.id.et_sex, R.id.et_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.tv_send_share://发布
                setPublishGirls();
                break;
            case R.id.linear_chose://从隐友中选择
                Intent intent = new Intent(activity, FriendsChooseActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.et_education:
                pvNoLinkOptionsEdu.show();
                break;
            case R.id.et_sex:
                showSexPopWindow();
                break;
            case R.id.et_address:
                showPickerView();
                break;
        }
    }



    /**
     * @return
     * @method
     * @description 性别选择
     * @date: 2018/9/26 14:20
     * @author: ljp
     */
    private void showSexPopWindow() {
        View view = View.inflate(this, R.layout.popo_sex, null);
        PopUtils.showPopupWindow(activity, view, false);
        TextView tvMan = (TextView) view.findViewById(R.id.sex_man);
        TextView tvWomen = (TextView) view.findViewById(R.id.sex_women);
        TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        tvMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSex.setText("男");
                sex = 1;
                PopUtils.hidePopupWindow();
            }
        });
        tvWomen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSex.setText("女");
                sex =2;
                PopUtils.hidePopupWindow();
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopUtils.hidePopupWindow();
            }
        });
    }
    /**
     * @return
     * @method
     * @description 城市数据解析
     * @date: 2018/9/27 11:22
     * @author: ljp
     */
    private void initJsonData() {//解析数据
        options1Items = new ArrayList<>();
        options2Items = new ArrayList<>();
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         * */
        String JsonData = Utils.getJson(this, "city.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean.DataBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<String> provinceList = new ArrayList<>();//该省的城市列表（第二级）
            String provinceName = jsonBean.get(i).getName();
            provinceList.add(provinceName);//添加城市
            for (int c = 0; c < jsonBean.get(i).getCities().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCities().get(c);
                cityList.add(cityName);//添加城市
            }
            /**
             * 添加城市数据
             */
            options2Items.add(cityList);
        }
    }
    /**
     * @return
     * @method
     * @description //Gson 解析
     * @date: 2018/9/27 11:23
     * @author: ljp
     */
    public ArrayList<JsonBean.DataBean> parseData(String result) {
        ArrayList<JsonBean.DataBean> detail = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray data = jsonObject.getJSONArray("data");
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean.DataBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.DataBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
    /**
     * @return
     * @method
     * @description 城市选择器
     * @date: 2018/9/27 11:46
     * @author: ljp
     */
    private void showPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) /*+
                        options3Items.get(options1).get(options2).get(options3)*/;
                // Toast.makeText(JsonDataActivity.this, tx, Toast.LENGTH_SHORT).show();
                province = options1Items.get(options1).getPickerViewText();
                city = options2Items.get(options1).get(options2);
               // province = options1Items.get(options1).getPickerViewText()+";"+options2Items.get(options1).get(options2);
                etAddress.setText(tx);
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.parseColor("#FF3B5E"))
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器*/
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        // pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }
    /**
     * @return
     * @method
     * @description 发布共享闺蜜信息
     * @date: 2019/1/16 16:37
     * @author: ljp
     */
    private void setPublishGirls() {
        nikName = etGirlsName.getText().toString().trim();
        String sex = etSex.getText().toString().trim();
        age = etAge.getText().toString().trim();
        education = etEducation.getText().toString().trim();
        redPack = etRedpacket.getText().toString().trim();
        phoneNumber = etPhoneNumber.getText().toString().trim();
        info = etBack.getText().toString().trim();
        if (TextUtils.isEmpty(nikName)) {
            toast_MakeText("请输入闺蜜昵称");
            return;
        }
        if (TextUtils.isEmpty(sex)) {
            toast_MakeText("请输入闺蜜性别");
            return;
        }
        if (TextUtils.isEmpty(age)) {
            toast_MakeText("请输入闺蜜年龄");
            return;
        }
        if (TextUtils.isEmpty(province)) {
            toast_MakeText("请选择闺蜜常住地");
            return;
        }
        if (TextUtils.isEmpty(redPack) || Integer.parseInt(redPack) < 50) {
            toast_MakeText("请输入不少于50元的牵线红包");
            return;
        }
        if (TextUtils.isEmpty(phoneNumber)) {
            toast_MakeText("请输入闺蜜联系方式");
            return;
        }
        if (TextUtils.isEmpty(education)) {
            toast_MakeText("请输入闺蜜最高学历");
            return;
        }
        if (TextUtils.isEmpty(info)) {
            toast_MakeText("请输入闺蜜介绍");
            return;
        }
        if (circlePictureAdapter.getTlist().size() == 0) {
            toast_MakeText("请至少选择一张照片");
            return;
        }
        if (TextUtils.isEmpty(height)) {
            toast_MakeText("请选择身高体重");
            return;
        }
        tvSendShare.setEnabled(false);
        setPictureList();
    }

    @OnClick(R.id.tv_height)
    public void onClick() {
        pvNoLinkOptions.show();
    }
    /**
     * @return
     * @method
     * @description 身高体重选择器
     * @date: 2018/9/27 11:54
     * @author: ljp
     */
    private void initNoLinkOptionsPicker() {// 不联动的多级选项
        pvNoLinkOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String str = statureList.get(options1) + "   " + weightList.get(options2);
                height = statureList.get(options1).substring(0,statureList.get(options1).length()-2) ;
                weight =  weightList.get(options2).substring(0,weightList.get(options1).length()-2) ;
                tvHeight.setText(str);
                Log.i(TAG, "onOptionsSelect: ------height--"+height+"----weight------"+weight);
            }
        })
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                    }
                })
                .setTitleText("身高体重选择")
                .setDividerColor(Color.parseColor("#FF3B5E"))
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvNoLinkOptions.setNPicker(statureList, weightList, null);
        pvNoLinkOptions.setSelectOptions(0, 1, 1);
    }
    /**
     * @return
     * @method
     * @description 学历选择器
     * @date: 2018/9/27 11:54
     * @author: ljp
     */
    private void initEduOptionsPicker() {// 不联动的多级选项
        pvNoLinkOptionsEdu = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String str = educationList.get(options1) ;
                etEducation.setText(str);
            }
        })
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                    }
                })
                .setTitleText("最高学历选择")
                .setDividerColor(Color.parseColor("#FF3B5E"))
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvNoLinkOptionsEdu.setNPicker(educationList, null, null);
        pvNoLinkOptionsEdu.setSelectOptions(0, 1, 1);
    }
    /**
     * @return
     * @method
     * @description 最高学历选择数据
     * @date: 2018/9/27 13:39
     * @author: ljp
     */
    private void initStatueEdu() {
        String[] stringArray = getResources().getStringArray(R.array.edu_list);
        educationList = new ArrayList<>();
        for (int i = 0; i < stringArray.length; i++) {
            educationList.add(stringArray[i]);
        }
    }
    /**
     * @return
     * @method
     * @description 身高体重数据
     * @date: 2018/9/27 13:39
     * @author: ljp
     */
    private void initStatue() {
        statureList = new ArrayList<>();
        weightList = new ArrayList<>();
        for (int i = 150; i <= 190; i++) {
            statureList.add(i + "cm"); // height: 150-180
        }
        for (int i = 30; i <= 150; i++) {
            weightList.add(i + "kg"); // weight: 30.0-150.0
        }
    }
}
